package handler

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"math/rand"
	"net/http"
	"strconv"
	"thread/api/params"
	"thread/global"
	"thread/model"
	"thread/pkg"
)

func Login(c *gin.Context) {

	req := params.LoginReq{}
	err := c.ShouldBind(&req)
	if err != nil {
		fmt.Errorf("绑定失败")
	}

	var user model.User

	global.DB.Debug().Where("mobile", user.Mobile).Find(&user)

	if user.ID == 0 {
		fmt.Errorf("手机号不存在")
	}

	if user.Password != req.Password {
		fmt.Errorf("密码错误")
	}
	handler, _ := pkg.TokenHandler(strconv.Itoa(int(user.ID)))

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "登录成功",
		"data":    handler,
	})

}

func SendSms(c *gin.Context) {

	sms := params.SendSms{}
	err := c.ShouldBind(&sms)
	if err != nil {
		fmt.Errorf("绑定失败")
	}
	code := rand.Intn(9000) + 1000
	sendSms, err := pkg.SendSms(sms.Mobile, strconv.Itoa(code))
	if err != nil {
		return
	}

	if *sendSms.Body.Code != "OK" {
		c.JSON(http.StatusOK, gin.H{
			"code":    500,
			"message": sendSms.Body.Message,
			"data":    nil,
		})
	} else {
		c.JSON(http.StatusOK, gin.H{
			"code":    200,
			"message": "短信发送成功",
			"data":    sms,
		})
	}

}

func Post(c *gin.Context) {

	pot := params.Post{}
	err := c.ShouldBind(&pot)
	if err != nil {
		fmt.Errorf("绑定失败")
	}

	var pos model.Post
	pos = model.Post{

		Title:   pot.Title,
		Content: pot.Content,
		Image:   pot.Image,
	}
	global.DB.Debug().Create(&pos)

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "帖子发布成功",
		"data":    pos,
	})
}
